package com.tlgen.orm.utils.xml;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;

public class XmlFileReader {

    // 高性能文件读取（兼容Java 8+）
    public static String readXmlFile(Path path) throws IOException {
        // 方案1：直接缓冲区读取（最佳性能）
        if (path.toFile().length() < 1024 * 1024) { // <1MB
            return new String(Files.readAllBytes(path), StandardCharsets.UTF_8);
        }

        // 方案2：缓冲流读取（大文件优化）
        return readLargeFile(path);
    }

    // 10行代码实现高效大文件读取
    private static String readLargeFile(Path path) throws IOException {
        StringBuilder content = new StringBuilder((int) Files.size(path));
        char[] buffer = new char[8192]; // 8KB缓冲池

        try (BufferedReader reader = Files.newBufferedReader(path)) {
            int charsRead;
            while ((charsRead = reader.read(buffer)) != -1) {
                content.append(buffer, 0, charsRead);
            }
        }
        return content.toString();
    }

    // 超高性能读取（内存映射，适用于>100MB文件）
    public static String readWithMappedBuffer(Path path) throws IOException {
        try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
            long fileSize = channel.size();
            MappedByteBuffer buffer = channel.map(
                    FileChannel.MapMode.READ_ONLY, 0, Math.min(Integer.MAX_VALUE, fileSize));

            byte[] bytes = new byte[(int) fileSize];
            buffer.get(bytes);
            return new String(bytes, StandardCharsets.UTF_8);
        }
    }

}